const utils = require('../../../../common/util/util')

Page({
  data: {
    nav: [
      {
        title: '最新',
        key: ''
      },
      {
        title: '热门',
        key: ''
      }
    ],
    active: 0,
    info: '',
    label: '',
    id: '',
    // readyMsg: 0,
    loading: true,
    page: 1,
    warning: true,
    list: [],
    isFixedTop: false,
    navbarInitTop: 0,
    statusBar: '',
    customBar: '',
    state:'navbar',
    openid:'',
    xPageReady:true
  },
  onShareAppMessage: function () {
    return {
      
    };
  },
  onLoad: function (options) {
    let that = this
    that.xInit() //列表
    that.xGetAggregate() //标题
    that.xInfo() //用户信息
    that.xReady() //消息通知
  },

  onShow: function () {
    let that =this
    if(getApp().globalData.scrollTop){
      wx.pageScrollTo({
        scrollTop:0,
        success:function(){
          getApp().globalData.scrollTop=false
        }
      })
    }
    // 发布页面修改头像
    if(getApp().globalData.InfoRefresh){
      this.xInfo() 
      getApp().globalData.InfoRefresh=false
    }
    // this.setData({
    //   page:1
    // })
  },
  onReachBottom: function (e) {
    let that = this
    that.setData({
      warning: false,
      // loading : true
    })
    that.xInit()
  },

  onPageScroll: function (e) {
    let that = this;
    var scrollTop = parseInt(e.scrollTop);
    if(scrollTop<=20){
      that.setData({
        isFixedTop: false
      });
    }else{
      that.setData({
        isFixedTop: true
      });
    }
  },
  
  xGetAggregate:function(){
    let that =this
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
          action: "community_aggregate_statistics"
         }
      }).then(res => {
        that.setData({
          aggregate:res.result
        })
    })
  },
  xInfo :function(){
    let that = this;
    wx.cloud.callFunction({
      name: 'user',
      data: {
          action: 'detail'
      }
    }).then(res => {
        let user = res.result
        that.setData({
            openid: user.user_id,
            user_info:user
        })
        
    })
  },
  xScroll: function () {
    let that = this;
    if (that.data.navbarInitTop == 0) {
      wx.createSelectorQuery().select('#navbar').boundingClientRect(function (rect) {
        if (rect && rect.top > 0) {
          var navbarInitTop = parseInt(rect.top);
          console.log(navbarInitTop)
          that.setData({
            navbarInitTop: navbarInitTop - 40
          });
        }
      }).exec();
    }
  },

  xSystem: function () {
    let that = this
    wx.getSystemInfo({
      success: (e) => {
        let custom = wx.getMenuButtonBoundingClientRect();
        that.setData({
          statusBar: e.statusBarHeight,
          customBar: custom.bottom + custom.top - e.statusBarHeight
        })
      }
    })
  },

  // xGetPostsInfo: function (id) {
  //   let that = this
  //   wx.cloud.callFunction({
  //     name: 'dynamic_content',
  //     data: {
  //       action: "get_count_by_label",
  //       label_id: id,
  //     }
  //   }).then(res => {
  //     let data = res.result
  //     console.log(res)
  //     that.setData({
  //       info: data[0],
  //       mylike:data[0].follow_group_status
  //     })
  //   })
  // },
  xDelete:function(e){
    let that =this
    let _id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let _data = {
        is_delete:1
    }
    wx.showModal({
      content: '确认删除这条帖子吗？',
      title: '警告',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          that.setData({
            [`list[${index}].is_delete`]: true,
          })
          wx.cloud.callFunction({
            name: 'dynamic_content',
            data: {
              action: "update_dynamic_content",
              _id: _id,
              dataObj: _data
            }
          }).then(res => {
            // that.xParReload()
          })
        }
      }
    })
    
  },
  xParReload: async function () {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    let active = that.data.active
    let page = that.data.page
    let list = []
    for (var i = 0; i < page; i++) {
      await wx.cloud.callFunction({
        name: 'dynamic_content',
        data: {
          action: "get_dynamic_content_list",
          type: active + 1,
          page_number: i + 1
        }
      }).then(res => {
        let data = res.result
        for (var k in data) {
          data[k].release_time = utils.formatTime_emotion(new Date(data[k].release_time))
          list.push(data[k])
        }
        that.setData({
          list: list
        })
        wx.hideLoading()
      })
    }
  },

  xInit: function () {
    let that = this
    let active = that.data.active
    let page = that.data.page
    let list = that.data.list
   
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "get_dynamic_content_list",
        page_number: page,
        type: active + 1
      }
    }).then(res => {
      let data = res.result
      for (var i in data) {
        data[i].release_time = utils.formatTime_emotion(new Date(data[i].release_time))
        list.push(data[i])
      }
      if (data.length === 0) {
        that.setData({
          list: list,
          page: page,
          loading: false,
          warning: true
        })
        setTimeout(() => {
          that.setData({
            warning: true
          })
        }, 2000)
      } else {
        page += 1
        that.setData({
          list: list,
          page: page,
          loading: false,
          page: page,
        })
      }
      that.setData({
        xPageReady:false
      })
      wx.hideLoading()
    })
  },

  xNavSelect: function (e) {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    let id = that.data.id
    let key = e.currentTarget.dataset.key
    that.setData({
      active: key,
      page: 1,
      list: [],
      loading: true,
      state:e.currentTarget.dataset.state
    })
    wx.pageScrollTo({
      scrollTop:  that.data.navbarInitTop,
    })
    that.xInit()
  },

  xToCreate: function () {
    let that = this
    wx.navigateTo({
        url: '/subtool/pages/community/add/index',
    })
  },

  xLike: function (e) {
    wx.showLoading({
      title: '刷新中',
    })
    let that = this
    let id = that.data.id
    let params = e.currentTarget.dataset
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "thumbs_up",
        _id: params.id,
      }
    }).then(res => {
      that.setData({
        [`list[${params.index}].me_thumbs_up`]: !params.state,
        [`list[${params.index}].total_thumbs_up`]: !params.state ? params.key + 1 : params.key - 1
      })
      if (!params.state) {
        wx.showToast({
          title: '点赞成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '取消成功',
          icon: 'none'
        })
      }
    })
  },

  xToDetail: function (e) {
    let id = e.currentTarget.dataset.id
    let openid = e.currentTarget.dataset.openid
    let totalcomment = e.currentTarget.dataset.totalcomment
    wx.navigateTo({
      url: '/subtool/pages/community/detail/index?id=' + id + '&openid=' + openid +'&totalcomment='+ totalcomment,
    })
  },

  xReady: function () {
    let that = this
    wx.cloud.callFunction({
      name: 'station_message',
      data: {
        action: "get_unread_message_count"
      }
    }).then(res => {
      let data = res.result
      that.setData({
        readyMsg: data
      })
    })
  },
  xToEditUser:function(){
    wx.navigateTo({
      url: '/subuser/pages/personal_information/index',
    })
  },
  // 重新编辑
  xToEdit:function(e){
    let that =this
    let index = e.currentTarget.dataset.index
    that.xParReload()
    wx.navigateTo({
      url: '/subtool/pages/community/add/index',
      success: function(res) {
        res.eventChannel.emit('xToAdd', that.data.list[index])
      }
    })
  },
  // 查看图片
  xPreviewImage:function(e){
    var url= e.currentTarget.dataset.files
    wx.previewImage({
      urls: url,
    })
  },
  xToNewMessage: function () {
    wx.navigateTo({
      url: '/subtool/pages/community/msg/index',
    })
    // wx.navigateTo({
    //   url: '/subsale/pages/news/index/index?id=200001',
    // })
  },

  back: function () {
    wx.navigateBack({
      delta: -1,
    })
  },

  xMyLike: function () {
    let that = this
    let id = that.data.id
    let _dataObj = {
      group_id: id
    }
    if(that.data.mylike==0){
      wx.showLoading({
        title: '关注中',
      })
    }else{
      wx.showLoading({
        title: '取关中',
      })
    }
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "follow_group",
        dataObj: _dataObj
      }
    }).then(res => {
      console.log("返回:", res.result)
      that.setData({
        mylike : that.data.mylike ==1 ? 0 : 1
      })
      wx.hideLoading()
    })
  }
})